package com.anjbo.common;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;

/**
 * Created by Administrator on 2017/4/1.
 */
public class FSUtil {

    private static final String URL = "http://182.254.149.92:9206";
    private static final HttpUtil httpUtil = new HttpUtil();

    public static String uploadReturnUrl(String path, File file) {
        String url = null;
        try {
            String result = upload(path, file);
            if (StringUtils.isNotEmpty(result)) {
                JSONArray jsonArray = new JSONArray(result);
                if (jsonArray.length() > 0) {
                    JSONObject jsonObject = jsonArray.getJSONObject(0);
                    url = jsonObject.getString("url");
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return url;
    }

    public static String upload(String path, File file) {
        ArrayList<File> files = new ArrayList<File>();
        files.add(file);
        return upload(path, files);
    }

    public static String upload(String path, List<File> files) {
        String result = null;
        if (StringUtils.isNotEmpty(path) && files != null && files.size() > 0) {
            IdentityHashMap<String, File> fileMap = new IdentityHashMap<String, File>();
            for (File file : files) {
                fileMap.put(new String("file"), file);
            }
            HashMap<String, String> pathMap = new HashMap<String, String>();
            pathMap.put("path", path);
            result = httpUtil.postFiles(URL + "/fs/img/upload", pathMap, fileMap);
        }
        return result;
    }


    public static void main(String[] args) {

        String ms_pic = uploadReturnUrl("MS_PIC", new File("e:/abc.jpg"));
        System.out.println(ms_pic);
    }
}
